import React from 'react';
import { HashRouter as Router, Routes, Route, Navigate, Link, useParams } from 'react-router-dom';
import { Layout, ConfigProvider } from '@douyinfe/semi-ui';
import UserList from './UserList';
import UserForm from './UserForm';
import './App.css';

const { Header, Content } = Layout;

/**
 * 导航组件
 * 负责渲染导航链接并保持channelId参数
 */
function Navigation() {
  const { channelId } = useParams();
  
  return (
    <nav>
      <Link to={`/${channelId}/users`}>用户列表</Link>
    </nav>
  );
}

/**
 * 应用主组件
 * 包含路由配置和导航菜单
 */
/**
 * 带导航的布局组件
 * 在路由内部渲染，可以获取到channelId参数
 */
function LayoutWithNavigation() {
  return (
    <Layout className="layout-container">
      <Header>
        <Navigation />
      </Header>
      <Content className="layout-content">
        <Routes>
          <Route path="users" element={<UserList />} />
          <Route path="users/create" element={<UserForm />} />
          <Route path="users/edit/:id" element={<UserForm />} />
        </Routes>
      </Content>
    </Layout>
  );
}

/**
 * 获取弹出层容器
 * 在微前端环境中，确保弹出层正确定位
 * @returns {HTMLElement} 弹出层容器元素
 */
function getPopupContainer() {
  const wujieContainer = document.querySelector('.wujie_iframe');
  if (wujieContainer) {
    return wujieContainer;
  }
  
  // 查找应用根容器
  const appContainer = document.querySelector('#root');
  if (appContainer) {
    return appContainer;
  }
  
  // 兜底使用 document.body
  return document.body;
}

function App() {
  return (
    <ConfigProvider 
      getPopupContainer={getPopupContainer}
    >
      <Router>
        <Routes>
          <Route path="/" element={<Navigate to="/default/users" replace />} />
          <Route path="/:channelId/*" element={<LayoutWithNavigation />} />
        </Routes>
      </Router>
    </ConfigProvider>
  );
}

export default App;
